package com.fruit.controller.app.order;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.druid.util.StringUtils;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.common.Page;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.OrderGood;
import com.fruit.pojo.order.OrderReason;
import com.fruit.pojo.order.OrderView;
import com.fruit.pojo.refund.OrderRufund;
import com.fruit.service.order.OrderManager;
import com.fruit.service.pay.PayManager;
import com.fruit.service.pic.PictureManager;
import com.fruit.util.MessagesCode;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

/**
 * APP订单controller
 * 
 * @author
 *
 */
@Controller
@RequestMapping(value = "/app/order/")
public class OrderController extends BaseController {

	@Autowired
	private OrderManager orderService;
	
	@Autowired
	private PictureManager PictureService;
	
	@Autowired
	private PayManager payService;

	// 查询订单列表
	@RequestMapping(value = "/getOrderList", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getOrderList(Page page, HttpServletRequest request, HttpSession session) {
		this.logBefore(logger, "查询订单列表");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, Object> parame = new HashMap<String, Object>();
		String userId = request.getParameter("userId");
		String state = request.getParameter("state");
		String[] split = null;
		if (page.getPage() <= 0 || StringUtils.isEmpty(userId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
			return resMap;
		}
		if(state !=null){
			split = state.split(",");
		}
		parame.put("start", (page.getPage() - 1) * page.getShowNumber());
		parame.put("number", page.getShowNumber());
		parame.put("userId", userId);
		parame.put("state", split);
		try {
			List<Map<String, Object>> orders = orderService.getOrderList(parame);
			if (orders.size() > 0) {
				 Map<String, Object> orderMap = new TreeMap<String, Object>(Collections.reverseOrder());
				for (Map<String, Object> map : orders) {
					if ("00".equals(map.get("state"))) {
						map.put("stateName", "未付款");
					}  else if ("02".equals(map.get("state"))) {
						map.put("stateName", "待发货");
					} else if ("03".equals(map.get("state"))) {
						map.put("stateName", "待收货");
					} else if ("04".equals(map.get("state"))) {
						map.put("stateName", "已完成");
					} else if ("05".equals(map.get("state"))) {
						map.put("stateName", "已取消");
					} else if ("06".equals(map.get("state"))) {
						map.put("stateName", "已退款");
					} 
					OrderGood g = new OrderGood();
					g.setGoodsId((int) map.get("goodsId"));
					g.setGoodsThumb((String) map.get("goodsThumb"));
					g.setNumber((int) map.get("number"));
					g.setTradePrice((BigDecimal) map.get("tradePrice"));
					g.setTitle((String) map.get("title"));
					g.setUnit((String) map.get("unit"));
					g.setUnitDesc((String) map.get("unitDesc"));
					long orderId = (long) map.get("orderId");
					if (!orderMap.containsKey(orderId + "s")) {
						OrderView o = new OrderView();
						String codePre = (String) map.get("codePre");
						String codeSuf = (String) map.get("codeSuf");
						o.setOrderCode(codePre + orderId + codeSuf);
						o.setOrderId(orderId);
						o.setCreateTime((String) map.get("createTime"));
						o.setTotalPrice((BigDecimal) map.get("totalPrice"));
						o.setState((String) map.get("state"));
						o.setSupplierName((String) map.get("supplier"));
						o.setStateName((String) map.get("stateName"));
						o.setRefundState((String) map.get("refundState"));
						o.getOrderGoods().add(g);
						orderMap.put(Long.toString(orderId) + "s", o);
					} else {
						OrderView o = (OrderView) orderMap.get(Long.toString(orderId) + "s");
						o.getOrderGoods().add(g);
					}
				}
				Collection<Object> valueCollection = orderMap.values();
				List<Object> resOrderList = new ArrayList<Object>(valueCollection);
				resMap.put("orderList", resOrderList);
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
			} else {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "NO-ORDER", "未产生订单!"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}

	// 确认收货
	@RequestMapping(value = "/updateOrderState", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateOrderState(HttpServletRequest request) {
		this.logBefore(logger, "确认收货");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			String orderId = request.getParameter("orderCode");
			if (StringUtils.isEmpty(orderId)) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
				return resMap;
			}
			String oid = orderId.substring(4, orderId.length() - 7);
			if (oid != null) {
				Order order = orderService.getOrder(oid);
				if (order == null) {
					resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "订单为空"));
					return resMap;
				}
				if ("03".equals(order.getState())) {
					order.setState("04");
					orderService.updateOrderState(order);
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "修改成功"));

				} else {
					resMap.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "修改失败"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "网络异常"));
		}
		this.logAfter(logger);
		return resMap;
	}

	// 查询订单详情
	@RequestMapping(value = "/getOrderDetails", method = { RequestMethod.GET, RequestMethod.POST,
			RequestMethod.OPTIONS })
	@ResponseBody
	public Map<String, Object> getOrderDetails(String orderCode, HttpServletRequest request) {
		this.logBefore(logger, "查询订单详情");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(orderCode)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
			return resMap;
		}
		Page page =new Page();
		String oid = orderCode.substring(4, orderCode.length() - 7);
		String codepre = orderCode.substring(0, 4);
		String codesuf = orderCode.substring(orderCode.length() - 7);
		page.getParams().put("oid", oid);
		page.getParams().put("codepre", codepre);
		page.getParams().put("codesuf", codesuf);
		try {
			resMap = orderService.getOrderDetails(page);
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}

	// 将订单设为不显示
	@RequestMapping(value = "/deleteOrder", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS })
	@ResponseBody
	public Map<String, Object> deleteOrder(String orderCode, Page page, HttpServletRequest request) {
		this.logBefore(logger, "将订单设为不显示");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(orderCode)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
			return resMap;
		}
		String oid = orderCode.substring(4, orderCode.length() - 7);
		String codepre = orderCode.substring(0, 4);
		String codesuf = orderCode.substring(orderCode.length() - 7);
		page.getParams().put("oid", oid);
		page.getParams().put("codepre", codepre);
		page.getParams().put("codesuf", codesuf);
		try {
			OrderView ov = orderService.getOrderDe(page);
			if (ov != null) {
				if ("05".equals(ov.getState()) || "04".equals(ov.getState())) {
					page.getParams().put("version", ov.getVersion());
					orderService.updateOrderShow(page);
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "删除成功"));
				} else {
					resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "此订单不能删除!"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	// 退款商品申请
		@RequestMapping(value = "/refund", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS })
		@ResponseBody
		public Map<String, Object> refund(String orderCode,Page page,HttpServletRequest request) {
			this.logBefore(logger, "退款商品申请");
			Map<String, Object> resMap = new HashMap<String, Object>();
			if (StringUtils.isEmpty(orderCode)) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
				return resMap;
			}
			String oid = orderCode.substring(4, orderCode.length() - 7);
			String codepre = orderCode.substring(0, 4);
			String codesuf = orderCode.substring(orderCode.length() - 7);
			page.getParams().put("oid", oid);
			page.getParams().put("codepre", codepre);
			page.getParams().put("codesuf", codesuf);
			try {
				List<OrderGood> orderGoods=orderService.getOrderGoods(page);
				if(orderGoods.size() >0){
					resMap.put("orderGoods", orderGoods);
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
			this.logAfter(logger);
			return resMap;
		}
	
	
	
	
	
		//申请退款
		@RequestMapping(value = "/orderRefund", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS })
		@ResponseBody
		public Map<String, Object> orderRefund(OrderRufund or,Page page,HttpServletRequest request) {
			this.logBefore(logger, "申请退款");
			Map<String, Object> resMap = new HashMap<String, Object>();
			if (or ==null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
				return resMap;
			}
			String oid = or.getOrderCode().substring(4, or.getOrderCode().length() - 7);
			String codepre = or.getOrderCode().substring(0, 4);
			String codesuf = or.getOrderCode().substring(or.getOrderCode().length() - 7);
			page.getParams().put("oid", oid);
			page.getParams().put("codepre", codepre);
			page.getParams().put("codesuf", codesuf);
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("file");
			InputStream in = null;
			if(file != null){
				try {
					in = file.getInputStream();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			try {
				OrderView ov = orderService.getOrderDe(page);
				if("04".equals(ov.getState()) || "05".equals(ov.getState()) || "06".equals(ov.getState())){
					resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "此订单不支持退款"));
					return resMap;
				}
				if(in != null){
					String path = "/refund/" + codepre + oid + codesuf;
					Map imagePath = PictureService.uploadPictureFile(in, path, "msg.png");
					String imageAddress = (String) imagePath.get("url");
					or.setApplicationPic(imageAddress);
				}
				or.setOrderId(Integer.parseInt(oid));
				int num=orderService.saveRefund(or,ov);
				if(num == 1){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "退款成功"));
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "退款失败"));
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
			this.logAfter(logger);
			return resMap;
		}

		
		@RequestMapping(value="/payResult",method = { RequestMethod.POST,RequestMethod.GET })
		@ResponseBody
		public Map<String, Object> result(Order or){
			Map<String, Object> resMap = new HashMap<String, Object>();
			
			try{
				//校验购物车产品类型
				resMap = payService.getTransaction(or);
				}catch(Exception e){
					e.printStackTrace();
					this.logError(logger, e.getMessage());
					resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
				}
				return resMap;
			
		}	
		
	// 取消订单
			@RequestMapping(value = "/cancelOrder", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS })
			@ResponseBody
			public Map<String, Object> cancelOrder(String orderCode,String id,HttpServletRequest request) {
				this.logBefore(logger, "取消订单");
				Map<String, Object> resMap = new HashMap<String, Object>();
				if (StringUtils.isEmpty(orderCode) || StringUtils.isEmpty(id)) {
					resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
					return resMap;
				}
				String oid = orderCode.substring(4, orderCode.length() - 7);
				try {
					Order order=orderService.getOrder(oid);
					if(order != null){
						if("00".equals(order.getState())){
							resMap=orderService.saveSalesService(order,id);
						}else{
							resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "此订单不能取消"));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					this.logError(logger, e.getMessage());
					resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
				}
				this.logAfter(logger);
				return resMap;
			}
		
		// 取消订单原因
		@RequestMapping(value = "/cancelReason", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS })
		@ResponseBody
		public Map<String, Object> cancelReason(HttpServletRequest request) {
			this.logBefore(logger, "取消订单原因");
			Map<String, Object> resMap = new HashMap<String, Object>();
			try {
				List<OrderReason> order=orderService.getOrderReason();
				if(order != null){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功"));
					resMap.put("reason", order);
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
			this.logAfter(logger);
			return resMap;
		}
		
		// 退款列表
		@RequestMapping(value = "/refundOrderList", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS })
		@ResponseBody
		public Map<String, Object> refundOrderList(Page page,String userId,HttpServletRequest request) {
			this.logBefore(logger, "退款列表");
			Map<String, Object> resMap = new HashMap<String, Object>();
			Map<String, Object> parame = new HashMap<String, Object>();
			if (StringUtils.isEmpty(userId)) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
				return resMap;
			}
			try {
				parame.put("start", (page.getPage() - 1) * page.getShowNumber());
				parame.put("number", page.getShowNumber());
				parame.put("userId", userId);
				resMap=orderService.getRefundOrderList(parame);
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
			this.logAfter(logger);
			return resMap;
		}

}
